define(
  ["xterm","websocket","crypto","webshell"],
  function( xt, ws, ct, wsh){
    function Index( container ){
      this.container = container;
      this.wsh = new wsh()
      var _that = this;

      this.init = function (){
        // 解决第一次登录成功也跳转回登录问题
        $(document).ready(function (){
          let url = window.location.href;
          if (!url.endsWith("/?#")) {
            window.location.href = url + "?#";
          }
          let num1 = Math.round(Math.random()* 360);
          let num2 = Math.round(Math.random()* 360);
          $('body').css({background: 'linear-gradient(to left bottom, hsl(' + num1 + ', 100%, 85%) 0%,hsl(' + num2 + ', 100%, 85%) 100%)'})
        })
        _that.term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
        // 换行并输入起始符“$”
        _that.term.prompt = () => {
          _that.term.write("\r\n$ ");
        };

         let selection="";
        //选中复制
        _that.term.onSelectionChange(function() {
          if (_that.term.hasSelection()) {
            selection = _that.term.getSelection();
          }
        });
        _that.term.attachCustomKeyEventHandler(function(ev) {
          //粘贴 ctrl+v
          if (ev.keyCode === 86 && ev.ctrlKey) {
            _that.client.sendClientData("\x00" + selection);
            selection = "";
          }
        });

        _that.container.find('#form').submit(_that.login)
        _that.container.find('#loginSftp').click(
          _that.loginSftp
        )
        window.addEventListener("resize", _that.resizeScreen);
      }

      // 获取容器宽高/字号大小，定义行数和列数
      this.rows = document.querySelector(".indexContainer").offsetHeight / 16 - 5;
      this.cols = document.querySelector(".indexContainer").offsetWidth / 9;
      this.term = new xt.Terminal({
        rendererType: "canvas", //渲染类型
        pid: 1,
        name: 'terminal',
        rows: parseInt(_that.rows), //行数
        cols: parseInt(_that.cols),
        convertEol: true, //启用时，光标将设置为下一行的开头
        scrollback: 500,//终端中的回滚量
        disableStdin: false, //是否应禁用输入。
        cursorStyle: 'underline', //光标样式
        cursorBlink: true, //光标闪烁
        tabStopWidth: 8, //制表宽度
        screenKeys: true, //Xterm下的快捷键
        theme: {
          foreground: '#58a6ff', //字体,LightGreen,Orange,SlateBlue,Magenta Purple Red Violet White Yellow
          background: '#2B2B2B', //背景色
          // foreground: "#7e9192", //字体
          // background: "#002833", //背景色
          cursor: "Orange", //设置光标
          lineHeight: 16
        }
      });


      this.client = new WebSocketClient();

      /**
       * 执行连接操作
       * @param {Object} params 连接参数
       * @param {String} divId 显示控件id
       */
      function connect(params, divId) {
        _that.term.open(document.getElementById(divId), true);
        //在页面上显示连接中...
        _that.term.write('\r\nConnecting...');
        //执行连接操作
        _that.client.connect({
          onError: function (error) {
            //连接失败回调
            _that.term.write('Error: ' + error + '\r\n');
          },
          onConnect: function () {
            //连接主机
            _that.client.send(params);
            $("#login").hide();
            $("#menu").show();
          },
          onClose: function () {
            //连接关闭回调
            _that.term.write("\rconnection closed");
            $("#login").show();
          },
          onData: function (data) {
            //收到数据时回调
            _that.term.write(data);
          }
        });
        _that.term.onData(e => {
          //键盘输入时的回调函数
          _that.client.sendClientData(e);
        })
      }
      this.params = {
        operate:'connect',
        host: '',//IP
        port: '22',//端口号
        username: '',//用户名
        password: ''//密码
      }
      // connect(params, 'terminal')

      this.loginParams = {};
      this.login = function() {
        let params = {
          operate:'connect',
          host: $("#host").val(),//IP
          port: $("#port").val(),//端口号
          username: $("#username").val(),//用户名
          password: _that.wsh.encrypt($("#password").val())//密码
        }
        _that.loginParams = params;
        // 修改页面标签
        document.title += " " + params.host;
        connect(params, 'terminal')
      }
      // login()
      /** 连接SFTP服务 */
      this.loginSftp =  function() {
        _that.loginParams.operate = 'sftp'
        window.open(window.location.href.replace('?#', 'sftp?params=' + encodeURIComponent(JSON.stringify(_that.loginParams))))
      }
      // 内容全屏显示-窗口大小发生改变时
      this.resizeScreen = function (size) {
        console.log("size", size);
        _that.term.scrollToBottom();
        try {
          // fitAddon.fit();
          // 窗口大小改变时触发xterm的resize方法，向后端发送行列数，格式由后端决定
          _that.term.onResize(size => {
            _that.client.send({ Op: "resize", Cols: cols, Rows: rows });
          });
        } catch (e) {
          console.log("e", e.message);
        }
      }


    }
    return Index;
  }
)
